<template>
    <div class="formBox" style="width: 100%;height:100%;">
        <bpm-header :title="processConfig.name"></bpm-header>
        <div style="height: calc( 100% - 64px );">
            <a-tabs class="rx-a-tabs" default-active-key="details"  @change="changeTabs($event)">
                <div slot="tabBarExtraContent" class="tabs-toolbar">
                    <process-tool-bar
                        v-if="!preview"
                        :processConfig="processConfig"
                        :def-id="localDefId"
                        :instId="instId"
                        :mainDefId="mainDefId"
                        :mainTaskId="mainTaskId"
                        :vars="vars"/>
                    <a-button v-else @click="bpmPreview">{{ $ti18('rxForm.commitBtn', '提交') }}</a-button>
                </div>
                <a-tab-pane key="details" :tab="i18n('list.detail', '详情')">
                    <div class="tab-center-bg">
                        <div class="tab-center" style="padding: 0 10px 10px">
                            <rx-forms v-if="processConfig.formType=='online'" ref="rxForms"></rx-forms>
                            <component v-else-if="processConfig.formType=='custom'" ref="customForm" :is="formComponent"
                                       :pk="pk"></component>
                            <component v-else-if="urlParamsShow" ref="outSideUrlForm" :is="formComponent" :pk="pk"
                                       :showUrl="outSideUrl" :urlParamData="urlParamData"></component>
                        </div>
                    </div>

                </a-tab-pane>
                <a-tab-pane key="flowChart" :tab="i18n('list.flowChart', '流程图')">
                    <bpm-image-view v-if="isShowImage" :def-id="localDefId" :formData="formDataJson"></bpm-image-view>
                </a-tab-pane>
            </a-tabs>
        </div>

    </div>
</template>
<script>
import {RxFit, Util} from '@lowcode/jpaas-common-lib';
import ProcessToolBar from "./ProcessToolBar";
import BpmInstApi from "@/api/bpm/core/bpmInst";
import FormPcApi from "@/api/form/core/formPc";
import RxForms from "./RxForms";
import userState from "@/assets/js/userState";
import BpmImageView from "@/views/modules/bpm/comps/BpmImageView";
import FlowUtil from "@/views/modules/bpm/js/FlowUtil";
import bpmHeader from "@/views/modules/bpm/core/component/bpmHeader";

export default {
    name: "bpm-inst-start",
    mixins: [userState, FlowUtil],
    props: {
        //流程定义ID
        defId: String,
        //流程实例ID
        instId: String,
        //通过主键直接启动流程
        pkId: String,
        //这个是从DialogView打开时需要用到的。
        menuParams: {
            type: String
        },

        mainDefId: String,
        mainTaskId: String,
        formData: Object,
        vars: Object,

        layerid: String,
        lydata: Object,
        destroy: Function,
        config: Object,
        preview: Boolean,
        startUserId: String
    },
    components: {
        ProcessToolBar,
        RxFit, bpmHeader,
        RxForms, BpmImageView
    },
    data() {
        var hasPk = false;
        if (this.pkId) {
            hasPk = true;
        }

        return {
            closed: false,
            title: this.i18n('list.processInit', '流程发起'),
            processConfig: {
                buttons: [],
                startConfirm: false,
                fillOpinion: false,
                assignFlowUsers: false,
                assignBatchFlowUsers: false,
                startCalFlowusers: false,
                //是否允许选择路径。
                allowSelectPath: false,
                formType: "online",
                hasPk: hasPk
            },

            formComponent: "",
            outSideUrl: "",
            urlParamData: [],
            urlParamsShow: false,
            pk: "",
            //流程定义KEY
            defKey: "",
            //流程定义ID
            localDefId: "",
            //是否从路由过来
            fromRoute: false,
            //根实例
            rootVm: true,
            allStleyWidth: {
                width: '100%',
            },
            allStyleBg: {
                backgroundColor: '#fff'
            },
            formDataJson:{},
            isShowImage:false
        }
    },
    beforeDestroy() {
        this.$bus.off("openFormDialogEvent");
    },
    created() {
        this.initParams();
        if (this.$bus.instance) {
            this.$bus.on("openFormDialogEvent", (obj) => {
                this.openFormDialogEvent(obj);
            });
        }
    },
    methods: {
        changeTabs(key){
            if(key=='flowChart'){
                this.getFormData();
            }else {
                this.isShowImage=false;
            }
        },
        getFormData() {
            let formType = this.processConfig.formType;
            let rxForms = this.$refs.rxForms;
            let customForm = this.$refs.customForm;
            if (formType == "online" && rxForms) {
                this.formDataJson = rxForms.getData();
            } else {
                this.formDataJson = customForm.getData();
            }
            this.isShowImage=true;
        },
        i18n(name, text, key) {
            return this.$ti18(name, text, "bpmInst", key);
        },
        openFormDialogEvent(formBoList) {
            var action = "boList";
            if (formBoList.isTreeDlg == "YES") {
                action = "boListTree";
            }
            let openObj = this.$router.resolve({
                name: 'openFormDoc',
                params: {
                    pkId: formBoList.id
                },
                query: {
                    action: action,
                    isDialog: formBoList.isDialog
                }
            });
            let href = openObj.href;
            window.open(href, "_blank");
        },
        initParams() {
            //从属性传入，这个一般用于 Util.open的方式打开。
            if (this.defId) {
                this.localDefId = this.defId;
                this.initProcessConfig();
            }
            //从弹框打开,使用DialogView 打开
            else if (this.menuParams) {
                this.handParams(JSON.parse(this.menuParams));
            } else if (this.config) {
                if (this.config.defId) {
                    this.localDefId = this.config.defId;
                }
                if (this.config.defKey) {
                    this.defKey = this.config.defKey;
                }
                this.initProcessConfig();
            }
            //通过路由获取参数
            else {
                var params;
                if (this.$route.meta.params) {
                    params = JSON.parse(this.$route.meta.params);
                } else {
                    params = this.$route.params;
                }
                this.fromRoute = true;
                this.handParams(params);
            }

        },
        handParams(params) {
            if (params.defId) {
                this.localDefId = params.defId;
            }
            if (params.defKey) {
                this.defKey = params.defKey;
            }
            this.initProcessConfig();
        },
        initProcessConfig() {
            var self_ = this;
            BpmInstApi.getProcessConfig(this.localDefId, this.defKey).then(res => {
                if (!res.success) {
                    this.$message.warning(res.message);
                    return;
                }
                self_.localDefId = res.data.defId;

                if (res.data) {
                    var config = Util.deepClone(self_.processConfig);
                    let buttonConfigs = [];
                    for (let i = 0; i < res.data.buttonConfigs.length; i++) {
                        //启动去除特送按钮
                        if (res.data.buttonConfigs[i].type != "specialDelivery") {
                            buttonConfigs.push(res.data.buttonConfigs[i]);
                        }
                    }
                    res.data.buttonConfigs = buttonConfigs;
                    self_.processConfig = Object.assign(config, res.data);
                }
                //处理表单配置。
                self_.handFormConfig(res.data);

                //加载表单。
                if (self_.processConfig.formType == "online") {
                    self_.initForm();
                } else {
                    self_.initCustomForm();
                }
            })
        },
        initCustomForm() {
            this.instId = this.instId ? this.instId : this.$route.params.instId;
            if (!this.instId) {
                if (this.config && this.config.instId) {
                    this.instId = this.config.instId;
                } else {
                    return;
                }
            }
            BpmInstApi.getPkByInstId(this.instId).then(res => {
                if (!res.success) {
                    return;
                }
                this.pk = res.data;
            })
        },
        //处理表单配置。
        handFormConfig(conf) {
            debugger;
            //startForm
            if (conf.startForm.formpc && conf.startForm.formpc.length > 0) {
                var form = conf.startForm.formpc[0];
                if (form && form.type == "custom") {
                    this.processConfig.formType = "custom";
                    this.formComponent = this.loadView(form.component);
                    return;
                }
                if (form && form.type == "outsideUrl") {
                    this.outSideUrl = form.component;
                    this.processConfig.formType = "outsideUrl";
                    this.formComponent = this.loadUrlView();
                    this.getFormPc(form.id);
                    return;
                }
            }
            //获取全局。
            if (conf.globalForm.formpc && conf.globalForm.formpc.length > 0) {
                var form = conf.globalForm.formpc[0];
                if (form && form.type == "custom") {
                    this.processConfig.formType = "custom";
                    this.formComponent = this.loadView(form.component);
                    return;
                }
                if (form && form.type == "outsideUrl") {
                    this.outSideUrl = form.component;
                    this.processConfig.formType = "outsideUrl";
                    this.formComponent = this.loadUrlView();
                    this.getFormPc(form.id);
                    return;
                }
            }
        },
        getFormPc(formId) {
            var self_ = this;
            if (!formId) {
                self_.urlParamsShow = true;
                return;
            }
            FormPcApi.get(formId).then(res => {
                if (!res.success) {
                    self_.$message.error(self_.i18n('URLFail', '获取外部URL表单失败：') + res.message);
                    return;
                }
                let data = res.data;
                if (data.urlParams) {
                    self_.replaceUrlParmaVal(data.urlParams);
                }
                self_.urlParamsShow = true;
                return;
            });
        },
        replaceUrlParmaVal(urlParams) {
            var curUser = this.user;
            var contextData = {
                userId: curUser.userId,
                defId: this.localDefId,
                instId: this.instId,
                taskId: "",
                nodeId: ""
            }
            var urlParamData = JSON.parse(urlParams);
            for (let i = 0; i < urlParamData.length; i++) {
                let param = urlParamData[i];
                if (param.paramType) {
                    let val = contextData[param.paramKeyVal];
                    param.paramKeyVal = val;
                }
            }
            this.urlParamData = urlParamData;
        },
        loadUrlView() {
            // 路由懒加载
            return require('@/layouts/UrlView.vue').default;
        },
        loadView(view) { // 路由懒加载
            return require(`@/views/${view}`).default;
        },
        async initForm() {
            var params = {defId: this.localDefId};
            var instId = this.instId ? this.instId : this.$route.params.instId;
            if (instId) {
                params.instId = instId;
            }

            //如果从外部传入主键
            if (this.pkId) {
                params.pkId = this.pkId;
            }

            let res = await BpmInstApi.getViewByDefId(params);
            if (!res.success) {
                this.$message.warning(res.message);
                return;
            }
            var data = res.data;
            var formData = data.formData;


            var curUser = this.user;
            var contextData = {
                type: "start",
                curUserId: curUser.userId,
                curUserName: curUser.fullName,
                account: curUser.account,
                deptId: curUser.deptId,
                curNodeId: "start",
                curNodeName: this.i18n('list.startNode', '开始节点'),
                instId: this.instId,
                defId: this.localDefId,
                tenantId: curUser.tenantId,
                tenantLabel: curUser.tenantLabel
            };
            formData[0].data = Object.assign(formData[0].data, this.formData);


            let _formAllConfig = JSON.parse(formData[0].metadata).formAllConfig;
            if (_formAllConfig) {
                this.allStleyWidth = {width: _formAllConfig.allWidth, maxWidth: _formAllConfig.allWidth}
                this.allStyleBg = {backgroundColor: _formAllConfig.bg}
            }
            this.$refs.rxForms.setData(formData, false, contextData);
        },
        closeWindow() {
            if (this.fromRoute) {
                this.$bus.emit("closeTab", {action: "current"})
            } else {
                Util.closeWindow(this, 'ok');
            }
        },
        bpmPreview() {
            Util.open({
                component: BpmImageView,
                curVm: this,
                title: this.i18n('list.processSimu', '流程仿真'),
                widthHeight: ['1024px', '600px'],
                data: {
                    defId: this.defId,
                    preview: true,
                    startUserId: this.startUserId,
                    formData: this.$refs.rxForms ? this.$refs.rxForms.getData() : {}
                }
            }, function (action) {
            });
        }
    },
    watch: {
        closed: function (val) {
            if (val) {
                this.closeWindow();
            }
        },
        '$route': {
            handler: function (val) {
                this.initParams();
            },
            deep: true
        }
    }
}
</script>
<style scoped>
.tabs-toolbar {
    display: inline-block;
}

.tab-center-bg {
    width: 100%;
    background: #F5F5F5;
    overflow: auto;
    height: calc( 100vh - 109px );
}

.tab-center {
    box-sizing: border-box;
    padding-top: 10px;
    max-width: 1300px;
    width: 80%;
    margin: auto;
    min-height: calc( 100vh - 121px );
    background: #fff;
    border-top: 10px solid #f5f5f5;
    border-bottom: 10px solid #f5f5f5;
    border-radius: 4px;
}

.rx-a-tabs >>> .ant-tabs-bar.ant-tabs-top-bar {
    margin-bottom: 0 !important;
}

</style>

